// We recommend using the configureStore method of the @reduxjs/toolkit package, which replaces createStore
import { createStore } from "redux";

export interface CounterState {
  value: number;
}

export enum CounterActionTypes {
  "incremented" = "counter/incremented",
  "decremented" = "counter/decremented",
}

interface Action<T extends string, P> {
  type: T;
  payload?: P;
}

const initialState: CounterState = {
  value: 0,
};

// 定义一个 reducer 函数
function counterReducer(
  state = initialState,
  action: Action<CounterActionTypes, CounterState>
) {
  switch (action.type) {
    case "counter/incremented":
      return { value: state.value + 1 };
    case "counter/decremented":
      return { value: state.value - 1 };
    default:
      return state;
  }
}

// 创建一个store仓库
const store = createStore(counterReducer);

// 订阅事件
store.subscribe(() => console.log(store.getState()));

// 派发事件
store.dispatch({ type: CounterActionTypes.incremented });

store.dispatch({ type: CounterActionTypes.incremented });

store.dispatch({ type: CounterActionTypes.decremented });
